package com.shipwe.loans.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shipwe.adapter.ShipweRecyclerViewAdapter
import com.shipwe.adapter.ShipweViewHolderHelper
import com.shipwe.loans.R
import com.shipwe.loans.databinding.DialogAuthWalletBinding
import com.shipwe.loans.pro.ShipweDialog
import com.shipwe.loans.utils.AppDensityUtil
import com.shipwe.loans.utils.AppLoadImageUtil
import com.shipwe.loans.utils.decoration.GridSpacingItemDecoration
import com.shipwe.loans.utils.event.AppEventPointHelper
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.weight.input.CustomEditText
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/21 13:45
 * @Annotation：绑卡dialog
 */
class AuthWalletAddDialog: ShipweDialog {
    private lateinit var binding: DialogAuthWalletBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    //开始选择时间
    private var startTime = 0L;

    var itemAdapter: ItemAdapter? = null

    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogAuthWalletBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initWalletTypeListView()
        showTypeDefaultView()
        checkSubmitStatus()
    }

    override fun initListener() {
        setOnClickListener(binding.walletClose)
        setOnClickListener(binding.walletSubmit)

        binding.walletMobile.addTextChangedListener(ITextWatcher)
        binding.walletMobileAgain.addTextChangedListener(ITextWatcher)
        binding.walletMobile.setInputFocusChangeListener(IFocusChangeListener)
        binding.walletMobileAgain.setInputFocusChangeListener(IFocusChangeListener)
        binding.walletMobile.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.walletMobile.clearFocus()
                true
            }
            false
        }
        binding.walletMobileAgain.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.walletMobileAgain.clearFocus()
                true
            }
            false
        }
    }

    override fun initData() {
        val bindList = arrayListOf<JSONObject>()
        val customize = CustomConfigsHelper.getShipweConfigData()
        if (customize != null){
            val walletChannels = customize.optJSONArray("walletChannels")
            if (walletChannels != null && walletChannels.length() > 0){
                for (i in 0..<walletChannels.length()){
                    val item = walletChannels.optJSONObject(i)
                    item.put("isSelect", false)
                    bindList.add(item)
                }
            }
        }
        itemAdapter!!.data = bindList
    }

    override fun onViewClick(v: View?) {
        when(v!!.id){
            R.id.walletClose -> {
                dismiss()
            }
            R.id.walletSubmit -> {//提交
                val typeObj = getSelectTypeItem() ?: return
                if (getPhoneNumber() != getPhoneNumberComplete()){
                    showTypeErrorView()
                    return
                }
                val duration = System.currentTimeMillis() - startTime
                val submitRemark = "${getPhoneNumber()}$$$duration"
                AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_ADD_SUBMIT,submitRemark)
                if(mCallback != null){
                    mCallback!!.onSubmitParams(typeObj,getPhoneNumber())
                }
                dismiss()
            }
        }
    }

    /**
     * 初始化类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initWalletTypeListView() {
        val layoutManager = GridLayoutManager(context,2)
        binding.walletTypeListView.layoutManager = layoutManager
        itemAdapter = ItemAdapter(binding.walletTypeListView)
        val leftDecoration = AppDensityUtil.dp2px(10f)
        binding.walletTypeListView.addItemDecoration(GridSpacingItemDecoration(2, leftDecoration, false))
        binding.walletTypeListView.adapter = itemAdapter!!
        binding.walletTypeListView.itemAnimator = DefaultItemAnimator()
        itemAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val model = itemAdapter!!.getItem(position)
            if (childView.id == R.id.walletItem) {//切换item
                for (i in 0..<itemAdapter!!.itemCount) {
                    val item = itemAdapter!!.getItem(i)
                    if (i == position) {
                        item.put("isSelect", true)
                    } else {
                        item.put("isSelect", false)
                    }
                }
                itemAdapter!!.notifyDataSetChanged()
                checkSubmitStatus()
                AppEventPointHelper.appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_USER_ACCOUNT_ADD_TYPE_CHECK, model.optString("desc"))
            }
        }
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
            checkSubmitStatus()
        }
    }

    /**
     * 焦点变化监听
     */
    private val IFocusChangeListener = CustomEditText.IInputFocusChangeListener { v, remark ->
        if (v.id == R.id.walletMobile){
            val mobile = binding.walletMobile.text.toString().trim()
            if (mobile.isNotEmpty()){
                AppEventPointHelper.appEventPointRequestAction(AppEventPointType.FORM.SHIPWE_FORM_USER_ACCOUNT_ADD_MOBILE,remark)
            }
        } else {
            val mobile = binding.walletMobileAgain.text.toString().trim()
            if (mobile.isNotEmpty()){
                AppEventPointHelper.appEventPointRequestAction(AppEventPointType.FORM.SHIPWE_FORM_USER_ACCOUNT_ADD_MOBILE,remark)
            }
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.walletMobile.setBackgroundResource(R.drawable.circle_fff6f6f6)
        binding.walletMobile.setTextColor(Color.parseColor("#FF100437"))
        binding.walletMobileAgain.setBackgroundResource(R.drawable.circle_fff6f6f6)
        binding.walletMobileAgain.setTextColor(Color.parseColor("#FF100437"))
    }

    /**
     * 设置号码错误提示
     */
    private fun showTypeErrorView(){
        binding.walletMobile.setBackgroundResource(R.drawable.circle_frame_ffff4d3e)
        binding.walletMobile.setTextColor(Color.parseColor("#FF4D3E"))
        binding.walletMobileAgain.setBackgroundResource(R.drawable.circle_frame_ffff4d3e)
        binding.walletMobileAgain.setTextColor(Color.parseColor("#FF4D3E"))
    }

    /**
     * 切换Ajouter按钮是否可点击
     */
    fun checkSubmitStatus(){
        if (getSelectTypeItem() != null && getPhoneNumber().isNotEmpty() && getPhoneNumberComplete().isNotEmpty() && (getPhoneNumber() == getPhoneNumberComplete())){
            binding.walletSubmit.isEnabled = true
//            binding.walletSubmit.alpha = 1f
        } else {
            binding.walletSubmit.isEnabled = false
//            binding.walletSubmit.alpha = 0.4f
        }
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        for (item in itemAdapter!!.data) {
            if (item.optBoolean("isSelect", false)){
                obj = item
                break
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun getPhoneNumber(): String{
        return binding.walletMobile.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun getPhoneNumberComplete(): String{
        return binding.walletMobileAgain.text.toString()
    }

    class ItemAdapter(recyclerView: RecyclerView?) : ShipweRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.dialog_auth_wallet_type_item) {
        override fun setItemChildListener(helper: ShipweViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.walletItem) //点击Item
        }
        override fun fillData(helper: ShipweViewHolderHelper, position: Int, model: JSONObject) {
            val isSelect = model.optBoolean("isSelect", false)
            val walletItem = helper.getView<LinearLayout>(R.id.walletItem)
            val walletLogo = helper.getImageView(R.id.walletLogo)
            val walletTitle = helper.getTextView(R.id.walletTitle)
            walletTitle.text = model.optString("desc")
            AppLoadImageUtil.instance.loadImageUrl(mContext,walletLogo,model.optString("logo"), R.drawable.load_holder)

            val walletSelect = helper.getImageView(R.id.walletSelect)
            if (isSelect) {
                walletItem.setBackgroundResource(R.drawable.radius10_ff7543ff)
                walletTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
                walletSelect.setImageResource(R.drawable.page_check_number_select)
            } else {
                walletItem.setBackgroundResource(R.drawable.radius10_fff6f6f6)
                walletTitle.setTextColor(Color.parseColor("#FFB8B5B4"))
                walletSelect.setImageResource(R.drawable.page_check_number_normal)
            }
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
        //确认
        fun onSubmitParams(typeObj: JSONObject,phoneNumber: String)
    }

    override fun show() {
        super.show()
        startTime = System.currentTimeMillis()
    }

    override fun onStart() {
        super.onStart()
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.DIALOG.SHIPWE_DIALOG_USER_ACCOUNT_ADD_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        AppEventPointHelper.appEventPointRequestAction(AppEventPointType.DIALOG.SHIPWE_DIALOG_USER_ACCOUNT_ADD_DISMISS,eventRemark)
    }
}